/*
 * Created by SharpDevelop.
 * User: Guy Fomi
 * Date: 2/5/2011
 * Time: 10:13 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using HtmlAgilityPack;
using System.Web.Script.Serialization;
using System.IO;
using TomatoSynchronizer.Store;

namespace TomatoSynchronizer
{
	/// <summary>
	/// Description of Site.
	/// </summary>
	public class Site
	{
		private string _url;
		private string _name;
		private string _user;
		private HtmlWeb _client;
		
		private LanguageStore _languageStore;
		
		public LanguageStore GetLanguageStore()
		{
			if(_languageStore == null)
			{
				if(_client == null)
				{
					throw new Exception("You must login first !!!");
				}
				else{
					_languageStore = new LanguageStore(this,_client);
				}
			}
			return _languageStore;
		}
		
		public void DeleteDatabase()
		{
			DirectoryInfo di = new DirectoryInfo("sites/" + _name);
			if(di.Exists)
			{
				di.Delete(true);
			}
		}
		
		public string User {
			get { return _user; }
			set { _user = value; }
		}
		private string _pass;
		
		public string Pass {
			get { return _pass; }
			set { _pass = value; }
		}
		
		public string Name {
			get { return _name; }
			set { _name = value; }
		}
		
		public string Url {
			get { return _url; }
			set { _url = value; }
		}
		
		public Site(string name,string url,string user,string pass)
		{
			this._name = name;
			this._url = url;
			this._user = user;
			this._pass = pass;
		}

		public bool Login(HtmlWeb client)
		{
			_client = client;
			bool succes = false;
			string reponse;
			if(!string.IsNullOrEmpty(_user) && !string.IsNullOrEmpty(_pass))
			{
				HtmlDocument doc = client.Load(_url + "/admin/json.php?action=login&language=en_US&module=login&user_name=" + _user + "&user_password=" + _pass);
				HtmlNode node = doc.DocumentNode.SelectSingleNode("/");
				reponse = node.InnerText;
				JavaScriptSerializer serialiser = new JavaScriptSerializer();//
				Dictionary<string,object> json = serialiser.Deserialize<Dictionary<string,object>>(reponse);
				foreach(string key in json.Keys)
				{
					if(key == "success")
					{
						bool.TryParse(json[key].ToString(),out succes);
					}
				}
			}
			
			return succes;
		}
		
	}
}
